package com.company.managesystem.common;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网络请求
 * Created by lqy on 2017/8/13.
 */

public abstract class DataFetch<T> {
    private static String TAG = "DataFetch";
    private Context _context;
    private String _url;
    private boolean _isArray = false;
    private Class<T> _classOft;

    /**
     * @param context  上下文
     * @param url      json请求地址，不包含hosturl
     * @param isArray  json是否为数组形式
     * @param classOft 要转换的javabean类型
     */
    public DataFetch(Context context, String url, boolean isArray, Class<T> classOft) {
        this._context = context;
        this._url = UrlUtils.hostUrl + url;
        this._isArray = isArray;
        this._classOft = classOft;
    }

    public void LoadingData(final boolean isRefresh) {
        final ProgressDialog progressDialog = new ProgressDialog(_context);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setTitle("请稍后");
        progressDialog.setMessage("正在通信");
        if (isRefresh) {
            progressDialog.show();
        }
        Log.v(TAG, "请求的地址：" + _url);
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder()
                .url(_url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v(TAG, "Something wrong!");
                if (!isRefresh) {
                    progressDialog.dismiss();
                }
                onDataLoadError();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseString = response.body().string();
                if (responseString == null || responseString.length() < 1) {
                    onDataLoadError();
                } else {
                    Log.v(TAG, "返回的json:" + responseString);
                    T data = null;
                    List<T> datas = null;
                    Type type;
                    if (_isArray) {
                        datas = jsonToList(responseString, _classOft);
                        onDataLoaded(datas);
                    } else {
                        type = new TypeToken<T>() {
                        }.getType();
                        data = new Gson().fromJson(responseString, _classOft);
                        onDataLoaded(data);
                    }
                    progressDialog.dismiss();
                }
                if (!isRefresh) {
                    progressDialog.dismiss();
                }
            }
        });
    }

    public static <T> ArrayList<T> jsonToList(String json, Class<T> classOfT) {
        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);

        ArrayList<T> listOfT = new ArrayList<>();
        for (JsonObject jsonObj : jsonObjects) {
            listOfT.add(new Gson().fromJson(jsonObj, classOfT));
        }
        return listOfT;
    }

    // 处理数组类型的json
    protected void onDataLoaded(List<T> data) {
    }

    // 处理单个对象类型的json
    protected void onDataLoaded(T data) {
    }

    // 请求错误处理
    protected abstract void onDataLoadError();

    // 请求成功后
    protected void onDataLoadSuccess(String result) {
    }
}
